Page({
  data: {
    selectedItems: [],
    count: 0,
    sum: '0.00',
    superchecked:false,
    address: '杭州市 余杭区  闲林街道  翡翠城东北区',
    shippingFrom: {
      type: "同城配送",
      name: "屈臣氏 (亲橙里店)",
    },
    shippingTime: {
      payTime: "11:00",
      receiveDay: "今天",
      receiveFormatDay: "04月16日",
    },
    commodity: [],
    isShow:false
  },
  onChangeAll(e) {
    console.log("onChangeAll",e);
    const checkedValues = e.detail.value; // 获取选中的子组件值   
    let total = 0;
    const itemList = this.data.commodity.map(item=>{
      total = total + (item.price*item.num)
      return {
        ...item,
        checked: checkedValues,
      }
    });
    console.log(itemList);
    this.setData({
      commodity:itemList,
      sum:total,
      count:itemList.length,
      superchecked: checkedValues,
    })
  },
  //todo 全选和单选之间联动有一定出错的概率，后期调整
  onChange(e) {
    console.log('on change e', e);
    const checkedValues = e.detail.value; // 获取选中的子组件值  
    console.log("onChange",checkedValues);
    console.log('commodity legnth',this.data.commodity.length); 
    const selectedItems = [];
    checkedValues.forEach(value => {
      const item = this.data.commodity.find(item => item.id === value);
      if (item) {
        selectedItems.push(item);
      }
    });
    console.log('selectedItems:',selectedItems)
    var total = selectedItems.reduce(function(acc, item) {
        return acc + (item.price*item.num);
      }, 0);
      
    this.setData({
      sum:total,
      count:selectedItems.length,
      commodity: this.data.commodity.map((item) => ({
        ...item,
        checked: checkedValues.includes(item.id),
      })),
      selectedItems: selectedItems,
      superchecked:checkedValues.length==this.data.commodity.length
    })
    console.log("选择的商品",this.data.selectedItems); 
  },
  //mosql数据库更新接口更新不了
  async decrease(event){
    const order = event.currentTarget.dataset.id;
    console.log("减少商品数量",event);
    if(order.num-1>0){
      const response =  await my.fncontext.callFunction({
        name:"shopCarUpdate",
        data:{
          "id":order.id,
          "number":order.num-1
        }
      });
      console.log("减少商品数量结果",response);
    }else{
      const ids = [];
      ids.push(order.id);
      const response    =  await my.fncontext.callFunction({
        name:"shopCarDelete",
        data:{
          "ids":ids
        }
      });
      console.log("删除单条购物车数据",response);
    }
    //重新获取购物车数据，渲染页面
    this.shopCarList();
  },
  //增加商品数量
  async increase(event){
    const order = event.currentTarget.dataset.id;
    console.log("增加商品数量",event);
    const response =  await my.fncontext.callFunction({
      name:"shopCarUpdate",
      data:{
        "id":order.id,
        "number":order.num+1
      }
    });
    console.log("增加商品数量",response);
    //重新获取购物车数据，渲染页面
    this.shopCarList();
  },
  onShow() {
    this.shopCarList();
    //this.fetchCurrentCommodities(this.data.activeTabId);
  },
  onLoad() {
    my.setNavigationBar({
      title: '购物车',
    });

  },
  async shopCarList(){
    const app = getApp();
    const userInfo = app.globalData.userInfo;
    console.log(userInfo);
    if(userInfo==null){
      abridge.alert({
        title: "获取个人信息失败，请稍后"
      })
      return
    }
    const shopCarList    =  await my.fncontext.callFunction({
      name:"shopCarList",
      data:{
        userId:userInfo.user_id
      }
    });
    console.log("shopCarList",shopCarList);
    const newData = shopCarList.result.map(item => {
      return {
        id: item._id,
        title: item.name,
        price: item.price,
        num: item.number,
        image: item.picUrl,
        description: item.description,
        productId: item.productId,
      };
    });
    if(newData.length == 0){
      this.setData({
        isShow:true
      })
    }else{
      this.setData({
        isShow:false
      })
    }
    this.setData({
      commodity:newData,
      superchecked:false,
      sum:'0.00',
      count:0
    })
  },
  pay(){
    const commodity = this.data.selectedItems; 
    const sum = this.data.count;
    const total = this.data.sum
    console.log(commodity.length); 
    if(commodity.length===0){
      abridge.alert({
        title: "请至少选择一个商品"
      })
      return
    }
    console.log(commodity); 
    my.navigateTo({
      url: '/pages/mall-statement/mall-statement',
      events: {
          // A 页面 接收 B 页面传过来的数据。
          pageB_Data(data) {
            console.log(data); // { "message": "hello～ 我是 pageB" }
          },
      },
      success: function(res) {
        const orderList = [
          {
            sum: sum,
            total: total,
            commodity:commodity
          }
        ]
        // A 页面向 B 页面 传值
        res.eventChannel.emit('orderList', { data: orderList })
      }
  })
  },
  //清空购物车  sdk不支持批量删除
  async deleteAll(){
    const response    =  await my.fncontext.callFunction({
      name:"shopCarRemoveAll",
      data:{
      }
    });
    console.log("清空购物车数据",response);
    //重新获取购物车数据，渲染页面
    this.shopCarList();
  },
  //删除单条购物车数据
  async delete(event){
    const ids = [];
    const id = event.currentTarget.dataset.id;
    ids.push(id);
    const response    =  await my.fncontext.callFunction({
      name:"shopCarDelete",
      data:{
        "ids":ids
      }
    });
    console.log("删除单条购物车数据",response);
    //重新获取购物车数据，渲染页面
    this.shopCarList();
  }
});
